import { FunctionComponent, useEffect } from 'react';
import { useRequest } from 'ahooks';
import { getQuestion } from '../../../api/question';
import { useParams } from 'react-router';
import styles from './index.module.scss';
import EditCanvas from '../../../components/quesitonComponents/editCanvas';
import useQuestionStore from '../../../zustandStore/questionStore';
import LeftPanel from './components/leftPanel';
import RightPanel from './components/rightPanel';
import EditHeader from './components/editHeader';
import useGetPageInfo from '../../../hooks/useGetPageInfo';
const Edit: FunctionComponent = () => {
  const resetComponents = useQuestionStore((state) => state.resetComponents);
  const changeSelectedId = useQuestionStore((state) => state.changeSelectedId);
  const { setPageInfo } = useGetPageInfo();
  const { id = '' } = useParams();
  const { loading, runAsync } = useRequest(
    (id) => {
      if (!id) Promise.reject('没有该问卷信息！');
      return getQuestion(+id);
    },
    { manual: true },
  );
  useEffect(() => {
    runAsync(id).then(({ data }) => {
      const { title, description, js, css } = data;
      //赋值components数据到store
      resetComponents(data.components);
      setPageInfo({ title, js, css, description });
    });
  }, [id]);
  return (
    <>
      <div className={styles.container}>
        <div>
          <EditHeader />
        </div>
        <div className={styles['content-wrapper']}>
          <div className={styles.content}>
            <div className={styles.left}>
              <LeftPanel />
            </div>
            <div className={styles.main} onClick={() => changeSelectedId('')}>
              <div className={styles['canvas-wrapper']}>
                <EditCanvas loading={loading} />
              </div>
            </div>
            <div className={styles.right}>
              <RightPanel />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default Edit;
